package jvm;

/**
 * @Description 演示对象回收过程
 * @Date 2023/2/16 14:13
 * @Created by wangjun
 */
public class FinalizeEscapeGC {

    public static FinalizeEscapeGC finalizeEscapeGC = null;

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        System.out.println("执行finalize()方法");
        finalizeEscapeGC = this;
    }

    public static void main(String[] args) throws InterruptedException {
        finalizeEscapeGC = new FinalizeEscapeGC();
        finalizeEscapeGC = null;
        // 进行对象的第一次回收
        System.gc();

        Thread.sleep(1000);
        // 这时会调用finalize()方法
        if (finalizeEscapeGC == null) {
            System.out.println("对象已死");
        } else {
            System.out.println("对象未死");
        }

        finalizeEscapeGC = null;
        // 进行对象的第二次回收
        System.gc();
        Thread.sleep(1000);
        // finalize()方法已经执行过了，直接回收对象
        if (finalizeEscapeGC == null) {
            System.out.println("对象已死");
        } else {
            System.out.println("对象未死");
        }
    }
}
